#!/usr/bin/env python
# coding: utf-8

import requests
from loguru import logger
from query_major_db import get_send_email,update_send_status
from datetime import datetime, timedelta
import json
import time
import schedule

headers = {
    "Content-Type": "application/json"
}
url = "https://site/wp-json/lpapi/v1/exchange/sendfeedbackemail"

logger.add("vot_spider.log")

def main():
    # 获取当前时间
    now = datetime.now()

    # 获取15天前的时间
    days_end = now - timedelta(days=15)
    print(days_end)
    # 获取15天前的零点时间
    midnight_end = datetime.combine(days_end.date(), datetime.min.time())
    print(midnight_end)
    res=get_send_email(midnight_end)
    print(res)
    if res:
        for r in res:
            data={
                "order_id":r["order_id"],
                "email_address":r["email"]
            }
            param = []
            param.append(data)
            send_res=send(param, r["site"])
            # 修改发送状态
            if send_res:
                update_send_status(r["id"], 2)

def send(params,site_str):
    site_url=url.replace("site",site_str)
    params=json.dumps(params)
    for i in range(3):
        #sleep(3)
        try:
            response = requests.post(site_url,headers=headers, data=params, timeout=15)
            assert response.status_code == 200
            json_result = json.loads(response.text)
            logger.info(f"Current query api for {site_url} - status|200")
            return True
        except Exception as e:
            logger.info(f"querying: {site_url} - {i}th - error: {e}")
        else:
            break
    else:
        logger.debug(f"Try query api for {site_url} - 3 times all failed")
        return False


# # 定义任务每天凌晨两点执行
# schedule.every().day.at("10:03").do(main)
#
# # 无限循环，检查并执行任务
# while True:
#     schedule.run_pending()
#     time.sleep(1)

if __name__ == '__main__':
    main()